<template>
	<view class="baseForm">
		<!-- 搜索&扫码 -->
		<view class="upload-scan">
			<view class="searchButton" @click="dropdownOpen = true">
				{{ options1[value1 - 1].label }}
				<u-icon name="arrow-down"></u-icon>
			</view>
			<u-search
				v-if="value1 === 1"
				v-model="searchText"
				shape="round"
				bgColor="#fff"
				:show-action="true"
				actionText="搜索"
				placeholder="请输入设备编号"
				:animation="true"
				:clearabled="true"
				class="search"
				@search="searchList"
				@clear="clearList"
				@custom="searchList"
			></u-search>
			<!-- <u-icon v-if="value1 === 1" name="scan" size="27px" :bold="false" @click="openScan"></u-icon> -->

			<!-- 原生扫码 https 协议 -->
			<u-icon v-if="value1 === 1" name="scan" size="27px" :bold="false" @click="scanHandle"></u-icon>

			<view v-if="value1 === 2" @click="showPositionPicker" class="flex input-box">
				<u--input v-model="position" prefixIcon="search" border="none" placeholder="请选择位置" readonly class="input-self"></u--input>
				<image @click.stop="clearInfo()" v-show="position" src="@/static/image/delete.png" />
			</view>
			<u-button v-if="value1 === 2" type="primary" class="search-btn" text="搜索" @click="searchList"></u-button>
		</view>
		<!-- <button @click="jumpAll">启动扫描scan-all</button> -->
		<!-- uni.navigate -->
		<!-- <button @click="jumpTo">启动扫描scan-qrcode</button>
		<view class="">
			{{decodedContent}}
		</view> -->
		<!-- <view id="interactive" class="viewport"></view>
		<button @click="startScanner()">启动扫描</button>
		<view class="output"></view> -->

		<!-- <view
      class="flex justify-between"
      style="padding: 0 15px; margin-bot tom: 1px"
    >
      <view @click="showPositionPicker" class="flex input-box">
        <u--input
          v-model="position"
          prefixIcon="search"
          border="none"
          placeholder="请选择位置"
          readonly
          class="input-self"
        ></u--input>
        <image
          @click.stop="clearInfo()"
          v-show="position"
          src="@/static/image/delete.png"
        />
      </view>
      <u-button
        type="primary"
        icon="search"
        class="search-btn"
        @click="searchList"
      ></u-button>
    </view> -->
		<!-- tab-bar切换 -->
		<!-- <view class="tab-bar">
			<u-tabs
				:current="activeTab"
				:list="tabList"
				:scrollable="false"
				:activeStyle="{
					color: '#007aff',
					fontWeight: 'bold'
				}"
				lineWidth="34px"
				lineHeight="2px"
				lineColor="#007aff"
				@change="changeTab"
			></u-tabs>
		</view> -->

		<!-- 当前作业 -->
		<view class="activeHeight">
			<!-- 列表 -->
			<u-list ref="tableScroll" @scrolltolower="scrolltolower" class="list" v-if="total" :height="listHeight" lowerThreshold="50px" :pagingEnabled="true">
				<u-list-item v-for="(item, index) in tableList" :key="item.id" @click="jump(item)">
					<view class="card">
						<view class="flex record-title">
							<text class="line1">{{ item.assetName }}</text>
							<text>
								{{ item.assetCode }}
							</text>
						</view>
						<view class="flex flex-col justify-between flex-1 h-full record-content-body">
							<view class="record-content">
								<view class="record-item">
									<text>设备状态</text>
									<text>
										{{ useDictionaryStore().filterDictName('assetStatus', item.assetStatus) }}
									</text>
								</view>
								<view class="record-item" v-show="item.assetModelNo || item.assetBrandName">
									<text>品牌型号</text>
									<text class="">
										<text>{{ item.assetModelNo }}</text>
										<text v-if="item.assetModelNo">-</text>
										<text>{{ item.assetBrandName }}</text>
									</text>
								</view>
								<view v-if="item?.manageDepartmentName" class="record-item">
									<text>管理部门</text>
									<text>{{ item.manageDepartmentName }}</text>
								</view>
								<view v-if="item?.locationName" class="record-item">
									<text>位置</text>
									<text>{{ item.locationName }}</text>
								</view>
							</view>
						</view>
					</view>
				</u-list-item>
			</u-list>
			<view class="flex justify-center" v-show="tableLoading">
				<u-loading-icon color="#000a7b"></u-loading-icon>
			</view>
			<!-- 空数据 -->
			<view v-show="tableList.length === 0 && !tableLoading">
				<u-empty mode="list" icon="http://cdn.uviewui.com/uview/empty/list.png"></u-empty>
			</view>
		</view>
		<!-- 树形选择器 -->
		<ba-tree-picker
			ref="positionPicker"
			:multiple="false"
			@select-change="positionChange"
			title="位置"
			:selectedData="showPositionValue"
			:localdata="positionList"
			valueKey="id"
			textKey="locationName"
			childrenKey="nodes"
		/>
		<u-action-sheet :closeOnClickOverlay="true" :actions="options1" :show="dropdownOpen" @select="selectClick" @close="dropdownOpen = false"></u-action-sheet>
	</view>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { onShow, onPullDownRefresh, onLoad } from '@dcloudio/uni-app';
import { http } from '@/utils/http';
import { PageResult, TabInfo } from '@/types/type';
import { getSecondTime } from '@/utils/common';
import { useDictionaryStore } from '@/stores/useDictionaryStore';
import { useEamStore } from '@/stores/useEamStore';
import BaTreePicker from '@/components/ba-tree-picker/ba-tree-picker.vue';
import { toScanCode } from '@/components/hs-scancode/scan.js';
// import MumuOneCode from '@/uni_modules/mumu-oneCode/components/mumu-oneCode/mumu-oneCode.vue'
// import Quagga from 'quagga';
// function jumpAll() {
// 	uni.navigateTo({
// 		url: '/pages/scan-new/scan-new'
// 	})
// }
// function jumpTo() {
// 	uni.navigateTo({
// 		url: '/pages/scan-qrcode'
// 	})
// }
// const decodedContent = ref('暂未识别');
// function startScanner() {
//     Quagga.init({
//             inputStream: {
//               name: "Live",
//               type: "LiveStream",
//               target: document.querySelector('#interactive'), // 目标DOM元素
//               constraints: {
//                 width: 640,
//                 height: 480,
//                 facingMode: "environment" // 使用后置摄像头
//               },
//             },
//             decoder: {
//               readers: [
//                 "code_128_reader",
//                 "ean_reader",
//                 "ean_8_reader",
//                 "upc_reader",
//                 "upc_e_reader",
//                 "code_39_reader",
//                 "code_39_vin_reader",
//                 "codabar_reader",
//                 "i2of5_reader",
//                 "2of5_reader",
//                 "code_93_reader",
//                 "qr_reader"
//               ],
//             },
//           }, (err) => {
//             if (err) {
//               console.error("初始化错误", err);
//               alert("初始化失败，请检查摄像头权限");
//               return;
//             }
//             console.log("初始化成功");
//             Quagga.start();
//           });

//           // 当检测到条形码或二维码时触发
//           Quagga.onDetected((result) => {
//             const code = result.codeResult.code;
//             decodedContent.value = code;
//             console.log("识别到的内容:", code);
//             Quagga.stop(); // 停止扫描，避免重复识别
//           });
// }

function scanHandle() {
	toScanCode({
		onlyFromCamera: true // 只允许通过相机扫码
	})
		.then((res) => {
			uni.showToast({
				icon: 'success',
				title: '扫码成功'
			});
			searchText.value = res;
			searchList();
		})
		.catch((e) => {
			uni.showToast({
				icon: 'error',
				title: e
			});
		});
}

// const activeTab = ref(0);
// const tabList = [{ name: '所有' }, { name: '待处理' }, { name: '处理中' }, { name: '已完成' }];
// function changeTab(val: TabInfo) {
// 	activeTab.value = val.index;
// 	searchList();
// }
const dropdownOpen = ref(false);
function openDrops(e) {
	dropdownOpen.value = true;
}
// 关闭筛选下拉
function closeDrops(e) {
	dropdownOpen.value = false;
}
const value1 = ref(1);
const options1 = [
	{
		label: '编号',
		name: '编号',
		value: 1
	},
	{
		label: '位置',
		name: '位置',
		value: 2
	}
];

function selectClick(index) {
	value1.value = index?.value;
	dropdownOpen.value = false;
}

// 显示选择器
const positionId = ref('');
const position = ref('');
const positionPicker = ref();
function showPositionPicker() {
	positionPicker.value._show();
}
//监听选择（ids为数组）
const showPositionValue = ref([]);
function positionChange(ids, names) {
	console.log('ids', ids);
	positionId.value = ids[0] ?? '';
	position.value = names ?? '';
	showPositionValue.value = ids[0] ? [ids[0]] : [];
}

// 清空数据
function clearInfo() {
	positionId.value = '';
	position.value = '';
	if (positionPicker.value?._reTreeList) {
		positionPicker.value._reTreeList();
	}
}
// 获取位置列表
const positionList = ref();
async function getPositionList() {
	const { data } = await http({
		method: 'POST',
		url: `/eam/locationInfo/getTree`,
		data: {}
	});
	positionList.value = data;
}

// 待完成数据
const tableList = ref([]);
const tableLoading = ref(false);
const current = ref(0);
const totalPage = ref(0);
const total = ref(0);

//列表高度
const listHeight = ref('');

onLoad(() => {
	// #ifdef H5
	listHeight.value = 'calc(100vh - 88px)';
	// #endif

	// #ifdef APP-PLUS
	listHeight.value = 'calc(100vh - 48px)';
	// #endif
	loadmore();

	getPositionList();
});

onPullDownRefresh(() => {
	searchList();
});

async function loadmore(type?: string) {
	try {
		current.value += 1;
		tableLoading.value = true;
		const result: PageResult<any> = await http({
			method: 'POST',
			url: '/eam/equAssetInfo/queryByPage',
			data: {
				current: current.value,
				size: 20,
				data: {
					searchAssetInfo: value1.value === 1 ? searchText.value : '',
					locationId: value1.value === 2 ? positionId.value : ''
				}
			}
		}).finally(() => {
			tableLoading.value = false;
		});
		const list = result.data;
		for (let i = 0; i < list.length; i++) {
			tableList.value.push(list[i]);
		}
		totalPage.value = result.page;
		total.value = result.total;
		type === 'refresh' && uni.stopPullDownRefresh();
	} catch (e) {
		console.log(e);
	}
}
const scrolltolower = () => {
	totalPage.value > current.value && loadmore();
};

// 点击扫码
const searchText = ref('');
function openScan() {
	/* #ifdef H5 */
	uni.showToast({
		icon: 'none',
		title: '请到安卓设备进行扫码'
	});
	/* #endif */
	// 只允许通过相机扫码
	uni.scanCode({
		scanType: ['barCode', 'qrCode'],
		onlyFromCamera: true,
		success: function (res) {
			searchText.value = JSON.parse(JSON.stringify(res.result));
			searchList();
			console.log('条码类型：' + res.scanType);
			console.log('条码内容：' + res.result);
		}
	});
}

// 列表搜索
function searchList() {
	current.value = 0;
	tableList.value = [];
	loadmore('refresh');
}

function clearList() {
	console.log('点击');
	searchText.value = '';
	searchList();
}

// 网页跳转
async function jump(item) {
	uni.navigateTo({
		url: `/pages/eam/equ/searchDeviceLedger/detail?assetId=${item.id}`,
		fail: () => {
			uni.showToast({
				title: '敬请期待',
				icon: 'error'
			});
		}
	});
}
</script>

<style lang="scss" scoped>
uni-page-body {
	height: 100%;
	background-color: #fbfbff;
}
.search {
	:deep(.u-search__content) {
		box-shadow: 0 1px 8px 0px rgb(19 10 236 / 8%);
	}
}
.baseForm {
	background-color: #fbfbff;
	.tab-bar {
		padding: 0 20px;
	}
	.upload-scan {
		padding: $uni-page-padding;
		padding-top: 5px;
		padding-bottom: 5px;
		display: flex;
		align-items: center;
		// box-shadow: 0 1px 10px 0px rgb(19 10 236 / 10%);
		.u-icon {
			margin-left: 8px;
		}
	}
	.u-line {
		padding: 10px 0;
	}
}
.list {
	.card {
		margin: $uni-page-padding;
		margin-top: 5px;
		margin-bottom: 4px;
		border-radius: 7px;
		padding: 12px 12px 0px 12px;
		transition: all 300ms ease;
		border: 1px solid #efefef;
		background-color: #fff;
		.card-flex {
			display: flex;
			align-items: flex-start;
		}
		.right {
			flex: 1;
		}
		.title {
			font-size: 14px;
			line-height: 40px;
			height: 40px;
			margin-top: 8px;
			font-weight: bold;
			color: #101010;
			border-top: 1px solid #e5ebff;
		}
		.uni-btn {
			float: right;
			font-size: 12px;
			height: 24px;
			line-height: 24px;
			padding: 0 15px;
			margin-top: 7px;
			font-weight: 400;
		}
		.des {
			font-size: 12px;
			line-height: 20px;
			margin-bottom: 3px;
		}
		.left {
			flex-basis: calc(50% + 10px);
		}
	}
}

.record-title {
	display: flex;
	justify-content: space-between;
	margin: 2px 0 2px 0;
	color: $primary-color;
	uni-text:nth-child(1) {
		font-weight: bold;
		font-size: 15px;
	}
	uni-text:nth-child(2) {
		font-weight: bold;
		font-size: 15px;
		min-width: 60px;
		text-align: right;
	}
}
.record-item {
	margin: 7px 0 !important;
	color: #8f8e94 !important;
	word-break: break-all;
}
.record-content .record-item > :first-child {
	min-width: 70px !important;
}
:deep(.input-box) {
	// width: calc(100% - 56px);
	width: 100%;
	// border: 0.5px solid #dadbde !important;
	border-radius: 100px;
	height: 32px;
	line-height: 32px;
	box-shadow: 0 1px 8px 0px rgb(19 10 236 / 8%);
	background-color: #fff;
	.u-input {
		pointer-events: none;
		height: 32px;
		line-height: 32px;
		padding-left: 10px !important;
	}
	.uni-input-placeholder {
		color: rgb(144, 147, 153) !important;
		font-size: 14px;
	}
	.u-icon__icon {
		font-size: 22px !important;
		line-height: 22px;
		font-weight: normal;
		top: 0px;
		color: rgb(144, 147, 153) !important;
	}
	image {
		padding: 6px 6px;
		width: 20px;
		height: 20px;
	}
}

:deep(.search-btn) {
	width: 32px;
	height: 34px;
	margin-left: 4px;
	border-radius: 4px;
	background-color: transparent;
	border: none;
	// .u-icon__icon {
	// 	margin-left: 5px;
	// 	color: rgb(96, 98, 102) !important;
	// 	font-size: 26px !important;
	// }
	.u-button__text {
		color: rgb(96, 98, 102) !important;
	}
}

:deep(.searchButton) {
	color: rgb(41, 121, 255);
	font-size: 14px;
	width: 52px !important;
	min-width: 52px !important;
	display: flex;
	justify-content: flex-start;
	.u-icon {
		margin-left: 2px !important;
		font-size: 14px;
		.u-icon__icon {
			font-size: 14px !important;
			line-height: 14px !important;
		}
	}
}

:deep(.u-dropdown) {
	flex: none !important;
	width: 52px;
	.u-cell-group__wrapper {
		// border: 1px solid rgb(214, 215, 217);
		// border-radius: 4px;
		border-right: 1px solid rgb(214, 215, 217);
		border-left: 1px solid rgb(214, 215, 217);
	}
	// .u-line { display: none;}
	.u-cell__body {
		padding: 8px 10px !important;
		// border: 1px solid #8f8e94;
	}
	.u-dropdown__content__mask {
		background-color: transparent;
	}
}
// :deep(.u-drawdown-item__content) {
// 	top: 88px !important;
// 	.common-search {
// 		display: flex;
// 		justify-content: flex-start;
// 		margin: 0 15px;
// 		padding: 13px 5px;
// 		border-bottom: 1px solid rgb(214, 215, 217);
// 	}
// }

// :deep(.dis-none){
// 		.u-dropdown__content{
// 			display: none;
// 		}
// 	}
</style>
